import express from 'express';
import fs from 'fs';
import path from 'path';
import cors from "cors";
import multer from 'multer';

const app = express();
const PORT = 3000;
// 配置 multer 存储选项
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './server/');
    },
    filename: function (req, file, cb) {
        cb(null, decodeURIComponent(file.originalname));
    }
});
const upload = multer({storage: storage});
// 中间件，解析 JSON 请求体
app.use(express.json());
app.use(cors());
const formulaList = ['ASUM', 'BCUM', 'CSUM'];

function parseFunctionString(funcString) {
    const regex = /([A-Za-z]+)\(([^)]*)\)/;
    const match = funcString.match(regex);

    if (!match) {
        return {functionName: '', params: []};
    }

    const functionName = match[1];
    const paramString = match[2];
    const params = paramString.split(',').map(param => param.trim()).filter(param => param !== '');

    return {functionName, params};
}

// 处理日志写入请求
// 前端用formdata传递一个file过来，把file存进server文件夹中
app.post('/log', upload.single('file'), (req, res) => {
    const file = req.file;
    if (!file) {
        return res.status(400).json({error: 'No file provided'});
    }
    try {
        // 文件已经保存到 ./server/ 目录下，不需要再写入
        res.status(200).json({message: 'File saved successfully'});
    } catch (error) {
        console.error(error);
        res.status(500).json({error: 'Failed to save file'});
    }
});

app.post('/formula', (req, res) => {
    const formulaString = req.query.formula;
    const valueList = req.body
    const {functionName, params} = parseFunctionString(formulaString);
    console.log(`Function Name: ${formulaString}`);
    console.log(`Parameters: ${valueList}`);
    let result = valueList.reduce((acc, cur) => {
        return acc + cur
    }, 0)
    res.status(200).json({functionName, params, result});
})
// 从server文件夹中把所有文件列表读取出来,以文件名数组的形式传回
app.get('/templates', (req, res) => {
    const files = fs.readdirSync('./server');
    res.status(200).json(files);
})

// 根据文件名获取文件流
app.get('/template/:filename', (req, res) => {
    const filename = req.params.filename;
    const filePath = path.join('./server', filename);
    const fileStream = fs.createReadStream(filePath);
    res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(filename)}"`);
    fileStream.pipe(res);
});

// 根据文件名删除文件
app.delete('/template/:filename', (req, res) => {
    const filename = req.params.filename;
    const filePath = path.join('./server', filename);
    fs.unlink(filePath, (err) => {
        if (err) {
            console.error(err);
            res.status(500).json({error: 'Failed to delete file'});
        } else {
            res.status(200).json({message: 'File deleted successfully'});
        }
    });
});

// 获取formula列表
app.get('/formula/list', (req, res) => {
    res.status(200).json(formulaList);
})


app.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

